package cn.bone.mima.digest;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class DigestDemo {

    // 使用的类是 MessageDigest
    public static void main(String[] args) {
        // 原文
        String input = "123abcd武汉";

        // 算法
        String algorithmMD5 = "MD5";
        String algorithmSHA1 = "SHA-1";
        String algorithmSHA256 = "SHA-256";
        String algorithmSHA512 = "SHA-512";

        String md5 = toHex(input, algorithmMD5);
        String sha1 = toHex(input, algorithmSHA1);
        String sha256 = toHex(input, algorithmSHA256);
        String sha512 = toHex(input, algorithmSHA512);

        // fa78995e4a4f18bfc6e0d2fbdd768cbf
        System.out.println(md5);
        // 32
        System.out.println(md5.length());
        // 3be762d3f8d0e0c4e8c73c8b268bcf6a6f4a6049
        System.out.println(sha1);
        // 40
        System.out.println(sha1.length());
        // eb0c2ca2e23baa1a3424343f49d78ba2f2da7d9eea86897b82911b6a5f9a8805
        System.out.println(sha256);
        // 64
        System.out.println(sha256.length());
        // 5801fb4ec639044f8ecd0e42b4c47029aae2b0b48915b0d0e945c00869661eb997e872c877cddc4653774161484366be1666d5674ae042cff48b400ff6d7a063
        System.out.println(sha512);
        // 128
        System.out.println(sha512.length());
    }

    public static String toHex(String input, String algorithm){
        // 创建消息摘要对象
        MessageDigest messageDigest = null;
        try {
            messageDigest = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        // 执行消息摘要算法
        byte[] digest = messageDigest.digest(input.getBytes());

        StringBuilder builder = new StringBuilder();
        for (byte b : digest) {
            // 把密文转成16进制
            String s = Integer.toHexString(b & 0xff);
            if(s.length()==1){
                builder.append("0");
            }
            builder.append(s);
        }
        String s = builder.toString();
        return s;
    }
}
